import type { IAppData, IParam, IHttpResponse } from '@/core';
import { setSessionStorage, getSessionStorage } from '@/core';
import { Http } from '@/http';
import {
	useAppStoreWithOut,
	useAuthResourceStoreWithOut,
	useViewCtxStoreWithOut,
} from '@/store';
import { getCookie } from 'qx-util';

/**
 * 权限守卫
 *
 * @class AuthGuard
 */
class AuthGuard {
	/**
	 * 权限守卫实例对象
	 *
	 * @private
	 * @static
	 * @type {AuthGuard}
	 * @memberof AuthGuard
	 */
	private static authGuard: AuthGuard;

	/**
	 * Creates an instance of AuthGuard.
	 * 私有化构造器，只能通过getInstance()获取实例对象
	 * @memberof AuthGuard
	 */
	private constructor() {}

	/**
	 * 获取权限守卫实例对象
	 *
	 * @static
	 * @return {*}  {AuthGuard}
	 * @memberof AuthGuard
	 */
	static getInstance(): AuthGuard {
		if (!this.authGuard) {
			this.authGuard = new AuthGuard();
		}
		return this.authGuard;
	}

	/**
	 * 权限守卫入口方法
	 *
	 * @param {string} url 请求路径
	 * @param {IParam} [params={}] 额外参数
	 * @return {Promise<boolean>}
	 * @memberof AuthGuard
	 */
	public authGuard(url: string, params: IParam = {}): Promise<boolean> {
		if (import.meta.env.VITE_MODE === 'R7') {
			return this.getAppliDataWithOld(url, params);
		} else {
			return this.getAppliDataWithNew(url, params);
		}
	}

	/**
	 * 老模式
	 *
	 * @private
	 * @param {string} url
	 * @param {IParam} [params={}]
	 * @return {*}  {Promise<any>}
	 * @memberof AuthGuard
	 */
	private getAppliDataWithOld(url: string, params: IParam = {}): Promise<any> {
		return new Promise((resolve: Function, reject: Function) => {
			this.getAppData(url, params).then((result: any) => {
				result ? resolve(true) : reject(false);
			});
		});
	}

	/**
	 * 新模式
	 *
	 * @private
	 * @param {string} url
	 * @param {IParam} [params={}]
	 * @return {*}  {Promise<any>}
	 * @memberof AuthGuard
	 */
	private getAppliDataWithNew(url: string, params: IParam = {}): Promise<any> {
		return new Promise((resolve: Function, reject: Function) => {
			const saasMode = App.getProjectSetting().saasMode;
			if (saasMode) {
				if (getSessionStorage('avtiveOrgData')) {
					this.getAppData(url, params).then((result: any) => {
						result ? resolve(true) : reject(false);
					});
				} else {
					this.getOrgsByDcsystem().then((result: boolean) => {
						if (!result) {
							reject(false);
						} else {
							this.getAppData(url, params).then((result: any) => {
								result ? resolve(true) : reject(false);
							});
						}
					});
				}
			} else {
				this.getAppData(url, params).then((result: any) => {
					result ? resolve(true) : reject(false);
				});
			}
		});
	}

	/**
	 * 获取AppData
	 * @param url 路由
	 * @param params 参数
	 * @returns Promise<boolean>
	 */
	private getAppData(url: string, params: IParam = {}): Promise<boolean> {
		return new Promise((resolve: Function, reject: Function) => {
			const get: Promise<IHttpResponse> = Http.getInstance().get(url);
			get
				.then((response: IHttpResponse) => {
					if (response.success) {
						let { data } = response;
						if (data) {
							const { initAppGlobal } = useViewCtxStoreWithOut();
							initAppGlobal(data);
							this.setActiveOrgData(data);
							if (localStorage.getItem('localData')) {
								const { addLocalData } = useAppStoreWithOut();
								addLocalData(
									JSON.parse(localStorage.getItem('localData') as string)
								);
							}
							const { addAppData } = useAppStoreWithOut();
							addAppData(data);
							const { commitAuthData } = useAuthResourceStoreWithOut();
							commitAuthData(data as IAppData);
						}
					}
					resolve(true);
				})
				.catch((error) => {
					App.login();
				});
		});
	}

	/**
	 * 通过租户获取组织数据
	 *
	 * @memberof AuthGuard
	 */
	private getOrgsByDcsystem(): Promise<boolean> {
		return new Promise((resolve: Function) => {
			const dcSystemId = App.getProjectSetting().dcSystemId;
			const tempViewParam = { srfdcsystem: dcSystemId };
			if (tempViewParam.srfdcsystem) {
				setSessionStorage('dcsystem', tempViewParam);
				const requestUrl = `/uaa/getbydcsystem/${tempViewParam.srfdcsystem}`;
				const get: Promise<IHttpResponse> = Http.getInstance().get(requestUrl);
				get
					.then((response: IHttpResponse) => {
						if (response.success) {
							const { data } = response;
							if (data && data.length > 0) {
								setSessionStorage('orgsData', data);
								setSessionStorage('activeOrgData', data[0]);
							}
							resolve(true);
						} else {
							resolve(false);
						}
					})
					.catch((error) => {
						App.login();
					});
			} else {
				console.warn('登录失败', '登录失败，请联系管理员');
				App.login();
			}
		});
	}

	/**
	 * @description 设置激活组织数据
	 * @param {IParam} data
	 * @memberof AuthGuard
	 */
     public setActiveOrgData(appData: IParam) {
		const localData = localStorage.getItem('activeOrgData');
		const activeOrgData = getSessionStorage('activeOrgData');
		if (activeOrgData) {
			return;
		}
		const params: IParam = {};
		if(localData){
			const item = JSON.parse(localData);
			Object.assign(params, {
				department_id: item.department_id,
				organization_id: item.organization_id,
				organizational_role_id: item.organizational_role_id,
			});
		} else if (
			appData.context &&
			appData.context.member_of &&
			appData.context.member_of.length > 0
		) {
			const item = appData.context.member_of[0];
			Object.assign(params, {
				department_id: item.department_id,
				organization_id: item.organization_id,
				organizational_role_id: item.organizational_role_id,
			});
		}
		
		if(localData){
			const item = JSON.parse(localData);
			Object.assign(params, {
				deploy_system_id: item.deploy_system_id,
				system_id: item.system_id,
			});
		} else if (
			appData.context &&
			appData.context.roles &&
			appData.context.roles.length > 0
		) {
			const item = appData.context.roles[0];
			Object.assign(params, {
				deploy_system_id: item.deploy_system_id,
				system_id: item.system_id,
			});
		}
		setSessionStorage('activeOrgData', params);
	}
}
export default AuthGuard;
